package com.gzl.demo.filter;
import org.springframework.core.annotation.Order;
import javax.servlet.*;
import javax.servlet.FilterConfig;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author tll
 * @create 2020/8/1 12:41
 * @Order(x) 里面的数越小 越优先执行
 * @WebFilter() 代表着这是个Filter类 并把它注入到容器中
 */
@Order(1)
//@WebFilter(initParams = {@WebInitParam(name = "nofilter",value = "/one,/two")})
public class FirstFilter implements Filter {

    /**
     * 不过滤的资源
     */
    private String[] nofilter;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //将不过滤的资源存入数组中
        String nofilterString = filterConfig.getInitParameter("nofilter");
        if (nofilterString!=null&&nofilterString.length()>0){
            nofilter = nofilterString.split(",");
        }

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response =(HttpServletResponse) servletResponse;
        boolean flag = isNofilter(request);
        if (flag){
            filterChain.doFilter(servletRequest,servletResponse);
        }else {
            request.getRequestDispatcher("/noRoot").forward(servletRequest,servletResponse);
            //response.sendRedirect("/noRoot");
        }

    }

    @Override
    public void destroy() {

    }
    /**
     *isNofilter  判断路径是否不需要过滤
     */
    public boolean isNofilter(HttpServletRequest request){
        String requestURI = request.getRequestURI();
        System.out.println(requestURI);
        for (String s : nofilter) {
            if (requestURI.contains(s)){
                return true;
            }
        }
        return false;
    }
}